package com.xmotor.service.impl;

import com.xmotor.common.utils.FileTypeUtil;
import com.xmotor.service.TestService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class TestServiceImpl implements TestService {

    @Value("${file.upload.storage-path}")
    private String storagePath;

    @Value("${file.upload.legal-pattern}")
    private String[] legalPattern;

    @Override
    public String uploadFile(MultipartFile multipartFile) {
        try {
            FileTypeUtil.isImage(multipartFile);//判断是否是图片
            String fileName = multipartFile.getOriginalFilename().toLowerCase();
            String dateDir = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
            String localdir = storagePath + dateDir;
            File dirFile = new File(localdir);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String fileType = fileName.substring(fileName.lastIndexOf("."));

            String realFileName = uuid + fileType;
            //D:/1-JT/jt-image/yyyy/MM/dd/uuid.jpg
            String realPath = localdir + "/" + realFileName;
            File realFile = new File(realPath);

            multipartFile.transferTo(realFile);
            String url = dateDir + "/" + realFileName;
            System.out.println("文件上传成功：" + url);
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件上传失败！");
            throw new RuntimeException(e);
        }

    }

    @Override
    public String getFileHeader(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new RuntimeException("请勿上传空文件！");
        }
        String fileHeader = null;
        InputStream is = null;
        try {
            is = file.getInputStream();
            byte[] b = new byte[4];//最多读取4个字节
            is.read(b,0,b.length);//从输入流中将最多 len 个字节的数据读入一个 byte 数组中
            fileHeader = bytesToHexString(b);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeInputStream(is);
        }
        return fileHeader;
    }

    private void closeInputStream(InputStream is) {
        if (null != is) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将要读取文件头信息的文件的byte数组转换成string类型表示
     */
    private String bytesToHexString(byte[] src){
        StringBuilder sb = new StringBuilder();
        if (src == null || src.length <= 0){
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            // 以十六进制（基数 16）无符号整数形式返回一个整数参数的字符串表示形式，并转换为大写
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v).toUpperCase();
            if (hv.length() < 2){
                sb.append(0);
            }
            sb.append(hv);
        }
        return sb.toString();
    }
}
